package com.me.myFramework.myAop.aop300.intercept.method;

import javax.annotation.Nonnull;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 自己实现 AOP-300：  <p></p>
 *
 * AOP联盟：该接口是执行方法增强的切面执行器，封装了如下公共逻辑：
 * 该执行目标方法？还是继续执行 advice？以及下一次该执行哪个 advice？
 *
 * @author ME
 * @date 2021/9/26
 */
public class ReflectiveMethodInvocation implements MethodInvocation {

    /** 代理类 */
    private Object proxy;
    /** 目标类 */
    private Object target;
    /** 要执行的目标方法 */
    private Method method;
    /** 目标方法的入参 */
    private Object[] args;
    
    /** 执行切面逻辑的拦截器 */
    private List<MethodInterceptor> interceptorList;
    
    private int currentInterceptorIndex = -1;

    public ReflectiveMethodInvocation(Object proxy, Object target, Method method, Object[] args, @Nonnull List<MethodInterceptor> interceptorList) {
        this.proxy = proxy;
        this.target = target;
        this.method = method;
        this.args = args;
        this.interceptorList = interceptorList;
    }

    /**
     * 切面类的执行器，由执行器决定执行 源方法（目标对象的方法）还是 advice（增强方法）？以及执行哪一个 advice？
     *
     * @return 返回值
     * @throws Throwable Throwable
     */
    @Override
    public Object proceed() throws Throwable {
        // TODO 切面执行器的具体执行逻辑，从 aop200.MethodBeforeAdviceInterceptor.invoke111 抽取而来
        Object retVal;
        if (currentInterceptorIndex < this.interceptorList.size() - 1) {
            MethodInterceptor interceptor = this.interceptorList.get(++currentInterceptorIndex);
            retVal = interceptor.invoke(this);
        }
        else {
            retVal = method.invoke(target, args);
        }
        
        return retVal;
    }

    public Object getProxy() {
        return proxy;
    }

    @Override
    public Object getThis() {
        return target;
    }

    @Override
    public Method getMethod() {
        return method;
    }

    @Override
    public Object[] getArguments() {
        return args;
    }
}
